package api;

import dao.DaoUser;
import dao.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //判断是否是登录状态
        HttpSession session = req.getSession(false);
        if(session == null){
            //此时没有登录
            resp.setStatus(403);
            return;
        }
        if(session.getAttribute("user") == null){
            //如果没有用户对象
            resp.setStatus(403);
            return;
        }
        resp.setStatus(200);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求中的用户名或密码
        //给请求对象设置字符集,防止输入的用户名或者密码是中文,也能进行处理
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        if(username == null || password == null || username.equals("") || password.equals("")){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入错误");
            return;
        }

        //此时需要判断是否正确
       User user = DaoUser.getUserByName(username);
        if(user == null){
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }
        if(!user.getPassword().equals(password)){
            //判断密码是否相等
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码错误");
            return;
        }

        //此时账号密码正确可以创建会话
        HttpSession session = req.getSession(true);//如果没有绘会话默认创建一个
        session.setAttribute("user",user);
        //登录成功此时可以跳转页面
        resp.sendRedirect("blog_list.html");
    }
}
